<template>
  <div class="change-password">
    <el-form ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="100px" class="demo-ruleForm" status-icon>
      <el-form-item label="原始密码" prop="pass">
        <el-input v-model="ruleForm2.pass" type="password" auto-complete="off"/>
      </el-form-item>
      <el-form-item label="新密码" prop="checkPass">
        <el-input v-model="ruleForm2.checkPass" type="password" auto-complete="off"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
        <el-button @click="resetForm('ruleForm2')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { changePassword } from '@/api/login'
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm2.checkPass !== '') {
          this.$refs.ruleForm2.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value === this.ruleForm2.pass) {
        callback(new Error('两次输入密码一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm2: {
        pass: '',
        checkPass: ''
      },
      rules2: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      const flag = this.check()
      if (!flag) {
        return false
      }
      changePassword(this.ruleForm2.pass, this.ruleForm2.checkPass).then((res) => {
        if (res.success) {
          this.$message.success({
            message: '修改成功',
            duration: 1000
          })
        } else {
          this.$message.error({
            message: res.msg,
            duration: 1000
          })
        }
      })
    },
    check() {
      if (this.ruleForm2.pass.trim() === '') {
        this.$message.error({
          message: '密码不能为空',
          duration: 1000
        })
        return false
      }
      if (this.ruleForm2.checkPass.trim() === '') {
        this.$message.error({
          message: '新密码不能为空',
          duration: 1000
        })
        return false
      }
      if (this.ruleForm2.checkPass.trim() === this.ruleForm2.pass.trim()) {
        this.$message.error({
          message: '两次密码不能一样',
          duration: 1000
        })
        return false
      }
      return true
    },
    resetForm(formName) {
      this.ruleForm2.pass = ''
      this.ruleForm2.checkPass = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.change-password {
  width: 300px;
  padding-top: 100px;
}
</style>
